/*!
 * 服务启动脚本
 */

CHANNEL_WEB = "web";

var express	= require("express")
,   app 	= module.exports = express()
,   util	= require("util")
,	bodyParser = require("body-parser")
,	methodOverride = require('method-override')
,   errorhandler = require('errorhandler')
,	cookieParser = require("cookie-parser")
    // 解释表单数据
,   multipart = require("connect-multiparty")
,	session = require("express-session")
,	RedisStore = require('connect-redis')(session)
,   router = require("./server/routes")
;
    
    socketAction = require("./server/routes/socketio")
,   config = require("./server/config")
;




// 设置视图目录
app.set('views', __dirname + '/server/views');
// 设置模板引擎
var vash = require("vash");
vash.config.modelName  = "t";
vash.config.debug = true;
// 模板文件后缀使用.html
app.engine(".html", vash.__express );
app.set('view engine', 'html');

app.set("trust proxy", true);

// APP 挂件
// ---------
// 设置表态目录
// static 为关键字, 故使用 express['static']
app.use( express.static( __dirname + '/server/public') );

// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: false }))
 
// parse application/json 
app.use(bodyParser.json());
 
// override with the X-HTTP-Method-Override header in the request 
app.use( methodOverride('X-HTTP-Method-Override') );
app.use( cookieParser() );

//Redis
app.use(session({
  resave: true,
  saveUninitialized: true,
	secret: "diandao.org", // 加密串
	cookie: { secure: true },
	store: new RedisStore({
		host: "127.0.0.1",
		port: "6379",
		db: 2 // redis 数据库
	}),
	name: 'esid'
}));

app.use(errorhandler({ dumpExceptions: true, showStack: true }));

app.get("/",function(req,res){
	res.send("Access Forbidden!");
});

app.get("/watcher", router.watcher );
app.post("/gather", multipart(), router.gather );

var server = app.listen(config.port,function(){
	var host = server.address().address
	var port = server.address().port
	console.log('WatcherServer listening at http://%s:%s', host, port)
})


// globals
io  = require("socket.io").listen(server);
io.gather = {
	threads:{}
};

/**
 * Authorize a session before it given access to connect to SocketIO
 */
// io.configure(function () {
//   io.set('authorization', function (handshakeData, callback) {
//     var sessionID = getCookie(handshakeData.headers.cookie, "sessionid");
//     var meetingID = getCookie(handshakeData.headers.cookie, "meetingid");

//     handshakeData.sessionID = sessionID;
//     // handshakeData.username = properties.username;
//     // handshakeData.meetingID = properties.meetingID;
//     callback(null, true); // good authorization

//     // redisAction.isValidSession(meetingID, sessionID, function(isValid) {
//     //   if(!isValid) {
//     //     console.log("Invalid sessionID/meetingID");
//     //     callback(null, false); //failed authorization
//     //   }
//     //   else {
//     //     redisAction.getUserProperties(meetingID, sessionID, function (properties) {
//     //       handshakeData.sessionID = sessionID;
//     //       handshakeData.username = properties.username;
//     //       handshakeData.meetingID = properties.meetingID;
//     //       callback(null, true); // good authorization
//     //     });
//     //   }
//     // });
//   });
// });

// When someone connects to the websocket. Includes all the SocketIO events.

io.sockets.on('connection', socketAction.SocketOnConnection);
